package com.qs.services;

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.qs.dao.UserSessionDAO;
import com.qs.dao.UserDAO;
import com.qs.entities.UserSession;
import com.qs.entities.User;
import com.qs.exceptions.ServiceException;

public class SessionService {
	
	protected final Logger log = LoggerFactory.getLogger(SessionService.class);
	
	private UserSessionDAO 	userSessionDao;
	private UserDAO 		userDao;
	
	public UserSession createSession(String email) throws ServiceException{
		log.debug("creating session email:"+email);
		try{
			User user =  userDao.findByEmail(email).get(0);
			UserSession session 	= new UserSession();
			session.sessionId 	= UUID.randomUUID().toString();
			session.user		= user;
			userSessionDao.save(session);
			return session;
		}
		catch(Exception exc){
			throw new ServiceException(exc.getMessage(), exc);
		}
	}
	
	public UserSession createSession(User user) throws ServiceException{
		log.debug("creating session userId:"+user.userId);
		try{
			UserSession session 	= new UserSession();
			session.sessionId 	= UUID.randomUUID().toString();
			session.user		= user;
			userSessionDao.save(session);
			return session;
		}
		catch(Exception exc){
			throw new ServiceException(exc.getMessage(), exc);
		}
	}
	
	public UserSession fetchSessionById(String sessionId) throws ServiceException {
		log.debug("fetching session id:"+sessionId);
		try{
			return userSessionDao.findById(sessionId);
		}
		catch(Exception exc){
			throw new ServiceException(exc.getMessage(), exc);
		}
	}
	
	public void updateSession(UserSession session) throws ServiceException{
		log.debug("updating session id:"+session.sessionId);
		try{
			userSessionDao.attachDirty(session);
		}
		catch(Exception exc){
			throw new ServiceException(exc.getMessage(), exc);
		}
	}
	
	public void updateUserSessionByExpiry(String session_id,boolean isExpiry) throws ServiceException{
		try{
			userSessionDao.updateUserSessionByExpiry(session_id,isExpiry);
		}
		catch(Exception exc){
			throw new ServiceException(exc.getMessage(), exc);
		}
	}
	

	public void setUserSessionDao(UserSessionDAO userSessionDao) {
		this.userSessionDao = userSessionDao;
	}

	public void setUserDao(UserDAO userDao) {
		this.userDao = userDao;
	}

	

}
